<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券ID" prop="couponId">
        <el-input
          v-model="queryParams.couponId"
          placeholder="请输入优惠券ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="该类型优惠券数量" prop="couponNum">
        <el-input
          v-model="queryParams.couponNum"
          placeholder="请输入该类型优惠券数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用张数" prop="couponUse">
        <el-input
          v-model="queryParams.couponUse"
          placeholder="请输入使用张数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="剩余张数" prop="couponSurplus">
        <el-input
          v-model="queryParams.couponSurplus"
          placeholder="请输入剩余张数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['usercou:usercou:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['usercou:usercou:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['usercou:usercou:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['usercou:usercou:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="usercouList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户领劵记录ID" align="center" prop="usercouId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="优惠券ID" align="center" prop="couponId" />
      <el-table-column
        label="该类型优惠券数量"
        align="center"
        prop="couponNum"
      />
      <el-table-column label="使用张数" align="center" prop="couponUse" />
      <el-table-column label="剩余张数" align="center" prop="couponSurplus" />
      <el-table-column label="截止时间" align="center" prop="couponEndtime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['usercou:usercou:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['usercou:usercou:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户领券记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usercouRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="优惠券ID" prop="couponId">
          <el-input v-model="form.couponId" placeholder="请输入优惠券ID" />
        </el-form-item>
        <el-form-item label="该类型优惠券数量" prop="couponNum">
          <el-input
            v-model="form.couponNum"
            placeholder="请输入该类型优惠券数量"
          />
        </el-form-item>
        <el-form-item label="使用张数" prop="couponUse">
          <el-input v-model="form.couponUse" placeholder="请输入使用张数" />
        </el-form-item>
        <el-form-item label="剩余张数" prop="couponSurplus">
          <el-input v-model="form.couponSurplus" placeholder="请输入剩余张数" />
        </el-form-item>
        <el-divider content-position="center">优惠券信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTbCoupon"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTbCoupon"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="tbCouponList"
          :row-class-name="rowTbCouponIndex"
          @selection-change="handleTbCouponSelectionChange"
          ref="tbCoupon"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column
            label="优惠券类型(1-满减,2-折扣,3-直扣)"
            prop="couponType"
            width="150"
          >
            <template #default="scope">
              <el-select
                v-model="scope.row.couponType"
                placeholder="请选择优惠券类型(1-满减,2-折扣,3-直扣)"
              >
                <el-option
                  v-for="dict in coupon_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="满减门槛金额(类型1需要)"
            prop="couponFull"
            width="150"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.couponFull"
                placeholder="请输入满减门槛金额(类型1需要)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="折扣率(0.9=9折)或直扣金额"
            prop="couponDeduction"
            width="150"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.couponDeduction"
                placeholder="请输入折扣率(0.9=9折)或直扣金额"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="最大折扣金额(类型2需要)"
            prop="couponMaxdeduction"
            width="150"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.couponMaxdeduction"
                placeholder="请输入最大折扣金额(类型2需要)"
              />
            </template>
          </el-table-column>
          <el-table-column label="总库存" prop="couponTotal" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.couponTotal"
                placeholder="请输入总库存"
              />
            </template>
          </el-table-column>
          <el-table-column label="剩余库存" prop="couponRemain" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.couponRemain"
                placeholder="请输入剩余库存"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Usercou">
import {
  listUsercou,
  getUsercou,
  delUsercou,
  addUsercou,
  updateUsercou,
} from "@/api/usercou/usercou";

const { proxy } = getCurrentInstance();
const { coupon_type } = proxy.useDict("coupon_type");

const usercouList = ref([]);
const tbCouponList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTbCoupon = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    couponId: null,
    couponNum: null,
    couponUse: null,
    couponSurplus: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户领券记录列表 */
function getList() {
  loading.value = true;
  listUsercou(queryParams.value).then((response) => {
    usercouList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    usercouId: null,
    userId: null,
    couponId: null,
    couponNum: null,
    couponUse: null,
    couponSurplus: null,
  };
  tbCouponList.value = [];
  proxy.resetForm("usercouRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.usercouId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户领券记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _usercouId = row.usercouId || ids.value;
  getUsercou(_usercouId).then((response) => {
    form.value = response.data;
    tbCouponList.value = response.data.tbCouponList;
    open.value = true;
    title.value = "修改用户领券记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usercouRef"].validate((valid) => {
    if (valid) {
      form.value.tbCouponList = tbCouponList.value;
      if (form.value.usercouId != null) {
        updateUsercou(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUsercou(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _usercouIds = row.usercouId || ids.value;
  proxy.$modal
    .confirm('是否确认删除用户领券记录编号为"' + _usercouIds + '"的数据项？')
    .then(function () {
      return delUsercou(_usercouIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 优惠券序号 */
function rowTbCouponIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 优惠券添加按钮操作 */
function handleAddTbCoupon() {
  let obj = {};
  obj.couponType = "";
  obj.couponFull = "";
  obj.couponDeduction = "";
  obj.couponMaxdeduction = "";
  obj.couponTotal = "";
  obj.couponRemain = "";
  tbCouponList.value.push(obj);
}

/** 优惠券删除按钮操作 */
function handleDeleteTbCoupon() {
  if (checkedTbCoupon.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的优惠券数据");
  } else {
    const tbCoupons = tbCouponList.value;
    const checkedTbCoupons = checkedTbCoupon.value;
    tbCouponList.value = tbCoupons.filter(function (item) {
      return checkedTbCoupons.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleTbCouponSelectionChange(selection) {
  checkedTbCoupon.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "usercou/usercou/export",
    {
      ...queryParams.value,
    },
    `usercou_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
